import JSEncrypt  from 'jsencrypt'
import NodeRSA from 'node-rsa'
import {
  SHA256,
  AES,
  enc,
  mode,
  pad
} from 'crypto-js'

// rsa_公钥
const PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRFEUvfOMbtB6HesAYXRZLkb1snNV1eaDXv7kP5QrqSy5TbbsjjdEwCe/paLHMIIYfiNGamCfl2Xi4uqEooveGkniJj6EwVTSeSxt3qeavGsTiarQjnRYqs6VW1YZyeiK4NJQztp3ENQ4m7nqtP7s9CuGLgkQU9DGcuJfdZ9YajwIDAQAB'

const encrypt_public = new JSEncrypt({
  default_key_size: 1024,
  default_public_exponent: 65537
})
encrypt_public.setPublicKey(PUBLIC_KEY)

const encrypt_private = new JSEncrypt({
  default_key_size: 1024,
  default_public_exponent: 65537
})
encrypt_private.setPrivateKey(PUBLIC_KEY)

// SHA256处理
export const sha256 = (content, publicKey) => {
  const res = SHA256(content)
  const sha256Str = res.toString()
  return sha256Str
}
// rsa公钥加密
export const rsa = (content, publicKey) => {

  return encrypt_public.encrypt(content)

  // const key = new NodeRSA({ b: 1024 })
  // key.importKey(publicKey, 'pkcs8-public-pem')
  // key.setOptions({ encryptionScheme: 'pkcs1' })//指定加密格式
  // return key.encrypt(content, 'base64')
}
// rsa私钥解密
export const decrypt = (content, decryptId) => {

  return encrypt_private.decrypt(content)

  // const key = new NodeRSA({ b: 1024 })
  // key.importKey(decryptId, 'pkcs8-private-pem')
  // key.setOptions({ encryptionScheme: 'pkcs1' })//指定加密格式
  // return key.decrypt(content, 'utf8')
}

const node_rsa_key = new NodeRSA({
  b: 1024
})
node_rsa_key.importKey(PUBLIC_KEY, 'pkcs8-public-pem')
node_rsa_key.setOptions({
  encryptionScheme: 'pkcs1'
}) // 指定加密格式

// rsa公钥解密
export const decryptPublic = (content, decryptId) => {
  // const key = new NodeRSA({
  //   b: 1024
  // })
  // key.importKey(decryptId, 'pkcs8-public-pem')
  // key.setOptions({
  //   encryptionScheme: 'pkcs1'
  // }) // 指定加密格式
  return node_rsa_key.decryptPublic(content, 'utf8')
}

// AES加密
export const AESEncode = (content, key = '1234567890123456') => {
  const keyStr = enc.Utf8.parse(key.substring(0, 16))
  const iv = enc.Utf8.parse(key.substring(16))
  const str = enc.Utf8.parse(content)
  const encrypted = AES.encrypt(str, keyStr, {
    mode: mode.CBC,
    padding: pad.Pkcs7,
    iv
  })
  return encrypted.toString()
}

// AES解密
export const AESDecode = (content, key = '1234567890123456') => {
  const keyStr = enc.Utf8.parse(key.substring(0, 16))
  const iv = enc.Utf8.parse(key.substring(16))
  const decrypt = AES.decrypt(content, keyStr, {
    mode: mode.CBC,
    padding: pad.Pkcs7,
    iv
  })
  return enc.Utf8.stringify(decrypt).toString()
}
